<script setup>
import { ref, onMounted, computed } from 'vue';
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from 'element-plus';
import { useUserStore } from '@/stores/user';
import { Search } from '@element-plus/icons-vue';

const userStore = useUserStore();
const loading = ref(false);
const riderInfo = ref({});
const historyOrders = ref([]);
const queryParams = ref({
  status: '',
  startDate: '',
  endDate: '',
  orderNo: ''
});

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '待取件', value: 'ASSIGNED' },
  { label: '配送中', value: 'PICKED' },
  { label: '已送达', value: 'DELIVERED' }
];

// 获取骑手信息
const getRiderInfo = async () => {
  try {
    if (userStore.userId) {
      const { data: res } = await request.get(`/rider/user/${userStore.userId}`);
      if (res) {
        riderInfo.value = res;
        getHistoryOrders();
      }
    }
  } catch (error) {
    console.error('获取骑手信息失败', error);
    ElMessage.error('获取骑手信息失败');
  }
};

// 获取历史订单
const getHistoryOrders = async () => {
  loading.value = true;
  try {
    if (riderInfo.value.id) {
      let url = '/rider/deliveries';
      let params = { riderId: riderInfo.value.id };
      
      // 如果选择了特定状态，则使用按状态查询的接口
      if (queryParams.value.status) {
        url = '/rider/deliveries/status';
        params.status = queryParams.value.status;
      }
      
      const { data: res } = await request.get(url, { params });
      if (res) {
        console.log('历史订单数据:', res); // 添加日志查看数据
        // 先根据日期过滤
        let filteredOrders = filterOrdersByDate(res);
        // 再根据订单号过滤
        if (queryParams.value.orderNo) {
          filteredOrders = filteredOrders.filter(order => 
            order.orderNo && order.orderNo.includes(queryParams.value.orderNo)
          );
        }
        historyOrders.value = filteredOrders;
      }
    }
  } catch (error) {
    console.error('获取历史订单失败', error);
    ElMessage.error('获取历史订单失败');
  } finally {
    loading.value = false;
  }
};

// 根据日期过滤订单
const filterOrdersByDate = (orders) => {
  if (!queryParams.value.startDate && !queryParams.value.endDate) {
    return orders;
  }
  
  return orders.filter(order => {
    const orderDate = new Date(order.createTime);
    
    // 检查起始日期
    if (queryParams.value.startDate) {
      const startDate = new Date(queryParams.value.startDate);
      startDate.setHours(0, 0, 0, 0);
      if (orderDate < startDate) {
        return false;
      }
    }
    
    // 检查结束日期
    if (queryParams.value.endDate) {
      const endDate = new Date(queryParams.value.endDate);
      endDate.setHours(23, 59, 59, 999);
      if (orderDate > endDate) {
        return false;
      }
    }
    
    return true;
  });
};

// 处理查询
const handleQuery = () => {
  getHistoryOrders();
};

// 重置查询条件
const resetQuery = () => {
  queryParams.value = {
    status: '',
    startDate: '',
    endDate: '',
    orderNo: ''
  };
  getHistoryOrders();
};

// 骑手取件
const handlePickup = async (delivery) => {
  try {
    await ElMessageBox.confirm(`确认已取件订单 ${delivery.orderNo || delivery.id} 吗？`, '确认取件', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    });
    
    await request.put('/rider/pickup', {
      deliveryId: delivery.id
    });
    
    ElMessage.success('取件成功');
    await getHistoryOrders();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取件失败', error);
      ElMessage.error(typeof error === 'string' ? error : '取件失败');
    }
  }
};

// 骑手送达
const handleDeliver = async (delivery) => {
  try {
    await ElMessageBox.confirm(`确认已送达订单 ${delivery.orderNo || delivery.id} 吗？`, '确认送达', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'success'
    });
    
    await request.put('/rider/deliver', {
      deliveryId: delivery.id
    });
    
    ElMessage.success('送达成功');
    await getHistoryOrders();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('送达失败', error);
      ElMessage.error(typeof error === 'string' ? error : '送达失败');
    }
  }
};

// 格式化状态
const formatStatus = (status) => {
  const statusMap = {
    'PENDING': '等待分配',
    'ASSIGNED': '待取件',
    'PICKED': '配送中',
    'DELIVERED': '已送达',
    // 添加订单状态的映射
    'PENDING_PAYMENT': '待付款',
    'PAID': '已付款',
    'SHIPPED': '已发货',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  };
  return statusMap[status] || status;
};

// 格式化支付方式
const formatPaymentType = (type) => {
  const paymentMap = {
    'ONLINE': '在线支付',
    'CASH': '货到付款'
  };
  return paymentMap[type] || type;
};

// 获取标签类型
const getTagType = (status) => {
  const typeMap = {
    'DELIVERED': 'success',
    'PICKED': 'warning',
    'ASSIGNED': 'info',
    'PENDING': 'info',
    // 添加订单状态的标签类型
    'PENDING_PAYMENT': 'info',
    'PAID': 'warning',
    'SHIPPED': 'warning',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  };
  return typeMap[status] || 'info';
};

// 获取支付方式标签类型
const getPaymentTagType = (type) => {
  return type === 'CASH' ? 'danger' : 'success';
};

onMounted(() => {
  getRiderInfo();
});
</script>

<template>
  <div class="history-orders">
    <el-card class="query-card">
      <template #header>
        <div class="card-header">
          <span class="title">查询条件</span>
        </div>
      </template>
      
      <el-form :model="queryParams" label-width="80px" inline>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" style="width: 150px">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单号">
          <el-input 
            v-model="queryParams.orderNo" 
            placeholder="请输入订单号" 
            style="width: 150px"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="起始日期" style="width: 250px">
          <el-date-picker
            v-model="queryParams.startDate"
            type="date"
            placeholder="选择起始日期"
            format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束日期" style="width: 250px">
          <el-date-picker
            v-model="queryParams.endDate"
            type="date"
            placeholder="选择结束日期"
            format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="list-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span class="title">历史订单</span>
        </div>
      </template>
      
      <div v-if="historyOrders.length === 0" class="empty-list">
        <el-empty description="暂无历史订单"></el-empty>
      </div>
      
      <div v-else class="orders-grid">
        <el-card 
          v-for="order in historyOrders" 
          :key="order.id"
          shadow="hover" 
          class="order-card"
        >
          <div class="order-header">
            <div class="order-title">
              <span class="order-no">订单号: {{ order.orderNo || '未知' }}</span>
              <span class="order-amount">¥{{ order.totalAmount || '0.00' }}</span>
            </div>
            <div class="order-status-row">
              <div class="status-group">
                <div class="status-label">配送状态:</div>
                <el-tag :type="getTagType(order.deliveryStatus)" size="small" class="status-tag">
                  {{ formatStatus(order.deliveryStatus) }}
                </el-tag>
              </div>
              
              <div class="status-group">
                <div class="status-label">订单状态:</div>
                <el-tag :type="getTagType(order.orderStatus)" size="small" effect="plain" class="status-tag">
                  {{ formatStatus(order.orderStatus) }}
                </el-tag>
              </div>
              
              <div v-if="order.paymentType" class="status-group">
                <div class="status-label">支付方式:</div>
                <el-tag 
                  :type="getPaymentTagType(order.paymentType)" 
                  size="small"
                  class="status-tag"
                >
                  {{ formatPaymentType(order.paymentType) }}
                </el-tag>
              </div>
            </div>
          </div>
          
          <div class="divider"></div>
          
          <div class="order-info">
            <div class="info-item">
              <span class="info-label">分配时间:</span>
              <span>{{ new Date(order.createTime).toLocaleString() }}</span>
            </div>
            
            <div class="info-item">
              <span class="info-label">完成时间:</span>
              <span>{{ order.actualDeliveryTime ? new Date(order.actualDeliveryTime).toLocaleString() : '未完成' }}</span>
            </div>
            
            <div class="info-item">
              <span class="info-label">送达地址:</span>
              <span>{{ order.deliveryAddress || '无地址信息' }}</span>
            </div>
            
            <div class="detailed-address" v-if="order.addressInfo?.detailedAddress && order.addressInfo.detailedAddress !== order.deliveryAddress">
              <span class="text-small text-gray">详细地址: {{ order.addressInfo.detailedAddress }}</span>
            </div>
            
            <div v-if="order.rating" class="rating-section">
              <span class="info-label">用户评分:</span>
              <el-rate 
                v-model="order.rating" 
                disabled 
                show-score 
                text-color="#ff9900"
              />
            </div>
            
            <div v-if="order.riderComment" class="comment-section">
              <span class="info-label">用户评价:</span>
              <span>{{ order.riderComment }}</span>
            </div>
            
          </div>
          
          <div class="divider"></div>
          
          <div class="order-actions">
            <!-- 待取件状态 -->
            <el-button 
              v-if="order.deliveryStatus === 'ASSIGNED'"
              type="primary" 
              @click="handlePickup(order)"
            >
              确认取件
            </el-button>
            
            <!-- 配送中状态 -->
            <el-button 
              v-if="order.deliveryStatus === 'PICKED'"
              type="success" 
              @click="handleDeliver(order)"
            >
              确认送达
            </el-button>
            
            <!-- 已送达状态 -->
            <el-tag 
              v-if="order.deliveryStatus === 'DELIVERED'"
              type="success"
              effect="dark"
              class="status-completed"
            >
              配送已完成
            </el-tag>
            
            <!-- 提示货到付款 -->
            <div class="cash-notice" v-if="order.paymentType === 'CASH' && order.deliveryStatus === 'PICKED'">
              <el-tag
                type="danger"
                effect="dark"
                size="small"
                class="tag-cash"
              >
                货到付款
              </el-tag>
            </div>
          </div>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.history-orders {
  padding: 20px;
}

.query-card, .list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.empty-list {
  padding: 40px 0;
}

.orders-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.order-card {
  transition: all 0.3s;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  padding-bottom: 60px;
}

.order-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
}

.order-header {
  margin-bottom: 15px;
}

.order-title {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.order-no {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.order-amount {
  font-size: 16px;
  color: #f56c6c;
  font-weight: bold;
}

.order-status-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.status-group {
  display: flex;
  align-items: center;
}

.status-label {
  font-size: 13px;
  color: #909399;
  margin-right: 5px;
}

.status-tag {
  margin-right: 2px;
}

.divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 15px 0;
}

.order-info {
  margin-bottom: 10px;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
  align-items: flex-start;
}

.info-label {
  color: #606266;
  margin-right: 8px;
  min-width: 70px;
  font-size: 14px;
}

.detailed-address {
  margin-top: 5px;
  margin-left: 78px;
  margin-bottom: 10px;
}

.rating-section,
.comment-section {
  margin-top: 10px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.text-gray {
  color: #909399;
  font-style: italic;
}

.text-small {
  font-size: 12px;
}

.payment-notice {
  margin: 15px 0;
}

.order-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: absolute;
  bottom: 0;
  left: 0;
  width: calc(100% - 40px);
  padding: 15px 20px;
  background-color: #f9f9f9;
  border-top: 1px solid #ebeef5;
}

.status-completed {
  font-size: 14px;
}

.cash-notice {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.tag-cash {
  white-space: nowrap;
}
</style>